<script setup lang="ts">
import { VaButton, defineVaDataTableColumns, useModal } from 'vuestic-ui'
import { MineData, MineStatus } from '../types'
import { PropType, computed, toRef } from 'vue'
import { Pagination, Sorting } from '../../../data/pages/minedata'
import { useVModel } from '@vueuse/core'

const statusText: Record<MineStatus, string> = {
  '': '',
  public: '公开',
  private: '私有',
  deleted: '已删除',
}
const statusColors: Record<MineStatus, string> = {
  '': '',
  public: 'info',
  private: 'warning',
  deleted: 'danger',
}

const columns = defineVaDataTableColumns([
  // { label: 'Full Name', key: 'fullname', sortable: true },
  // { label: 'Email', key: 'email', sortable: true },
  // { label: 'Username', key: 'username', sortable: true },
  // { label: 'Role', key: 'role', sortable: true },
  // { label: 'Projects', key: 'projects', sortable: true },
  // { label: ' ', key: 'actions', align: 'right' },
  { label: '权限管理', key: 'actions', align: 'left' },
  { label: '样本名称', key: 'name', sortable: true },
  { label: '图片数量', key: 'number', sortable: true },
  { label: '描述', key: 'description', width: '250px', sortable: false, tooltip: true },
  { label: '状态', key: 'status', sortable: false },
  { label: '授权数', key: 'auth_number', sortable: true },
  { label: '上传时间', key: 'upload_time', width: '180px', sortable: true },
  { label: '地址', key: 'path', sortable: false },
  // { label: ' ', key: 'actions', align: 'right' },
])

const props = defineProps({
  data: {
    type: Array as PropType<MineData[]>,
    required: true,
  },
  loading: { type: Boolean, default: false },
  pagination: { type: Object as PropType<Pagination>, required: true },
  sortBy: { type: String as PropType<Sorting['sortBy']>, required: true },
  sortingOrder: { type: String as PropType<Sorting['sortingOrder']>, required: true },
})

const emit = defineEmits<{
  (event: 'edit-data', data: MineData): void
  (event: 'change-status', data: MineData): void
  (event: 'delete-data', data: MineData): void
  (event: 'view-data', data: MineData): void
  (event: 'update:sortBy', sortBy: Sorting['sortBy']): void
  (event: 'update:sortingOrder', sortingOrder: Sorting['sortingOrder']): void
}>()

const data = toRef(props, 'data')
const sortByVModel = useVModel(props, 'sortBy', emit)
const sortingOrderVModel = useVModel(props, 'sortingOrder', emit)

// const roleColors: Record<MineStatus, string> = {
//   admin: 'danger',
//   data: 'background-element',
//   owner: 'warning',
// }

const totalPages = computed(() => Math.ceil(props.pagination.total / props.pagination.perPage))

const { confirm } = useModal()
const onStatusChange = async (data: MineData) => {
  let agreed = undefined
  if (data.status === 'private') {
    agreed = await confirm({
      title: '公开样本',
      message: `你确定要公开“${data.name}”吗?`,
      okText: '公开',
      cancelText: '取消',
      size: 'small',
      maxWidth: '380px',
    })
  } else if (data.status === 'public') {
    agreed = await confirm({
      title: '隐藏样本',
      message: `你确定要隐藏“${data.name}”吗?`,
      okText: '隐藏',
      cancelText: '取消',
      size: 'small',
      maxWidth: '380px',
    })
  }
  if (agreed) {
    emit('change-status', data)
  }
}
const onUserDelete = async (data: MineData) => {
  const agreed = await confirm({
    title: '删除样本',
    message: `你确定要删除“${data.name}”吗?`,
    okText: '删除',
    cancelText: '取消',
    size: 'small',
    maxWidth: '380px',
  })

  if (agreed) {
    emit('delete-data', data)
  }
}

const onUserView = async (data: MineData) => {
  emit('view-data', data)
}
</script>

<template>
  <VaDataTable
    v-model:sort-by="sortByVModel"
    v-model:sorting-order="sortingOrderVModel"
    :columns="columns"
    :items="data"
    :loading="$props.loading"
  >
    <template #cell(name)="{ rowData }">
      <div style="font-weight: bolder" lass="ellipsis max-w-[230px] lg:max-w-[450px]">
        {{ rowData.name }}
      </div>
    </template>
    <template #cell(number)="{ rowData }">
      <span class="number">
        {{ rowData.number }}
      </span>
    </template>
    <template #cell(description)="{ rowData }">
      <span class="description">
        {{ rowData.description }}
      </span>
    </template>
    <template #cell(status)="{ rowData }">
      <VaBadge :text="statusText[rowData.status]" :color="statusColors[rowData.status as MineStatus]" />
    </template>
    <template #cell(auth_number)="{ rowData }">
      <span class="auth_number">
        {{ rowData.auth_number }}
      </span>
    </template>
    <template #cell(path)="{ rowData }">
      <div class="address">
        {{ rowData.path }}
      </div>
    </template>
    <template #cell(upload_time)="{ rowData }">
      <div v-if="rowData.upload_time" class="time">
        {{ rowData.upload_time }}
      </div>
    </template>
    <template #cell(actions)="{ rowData }">
      <div class="flex justify-start gap-2">
        <VaButton
          v-if="rowData.status === 'public'"
          preset="primary"
          size="small"
          icon="mso-hide_source"
          aria-label="编辑样本"
          @click="onStatusChange(rowData as MineData)"
        />
        <VaButton
          v-if="rowData.status === 'private'"
          preset="primary"
          size="small"
          icon="mso-cloud_upload"
          aria-label="编辑样本"
          @click="onStatusChange(rowData as MineData)"
        />
        <VaButton
          v-if="rowData.status !== 'deleted'"
          preset="primary"
          size="small"
          icon="visibility"
          aria-label="预览"
          @click="onUserView(rowData as MineData)"
        />
        <VaButton
          v-if="rowData.status !== 'deleted'"
          preset="primary"
          size="small"
          icon="mso-delete"
          color="danger"
          aria-label="删除样本"
          @click="onUserDelete(rowData as MineData)"
        />
      </div>
    </template>
  </VaDataTable>

  <div class="flex flex-col-reverse items-center justify-between gap-2 py-2 md:flex-row">
    <div>
      <b>{{ $props.pagination.total }} results.</b>
      Results per page
      <VaSelect v-model="$props.pagination.perPage" class="!w-20" :options="[15, 50, 100]" />
    </div>

    <div v-if="totalPages > 1" class="flex">
      <VaButton
        preset="secondary"
        icon="va-arrow-left"
        aria-label="Previous page"
        :disabled="$props.pagination.page === 1"
        @click="$props.pagination.page--"
      />
      <VaButton
        class="mr-2"
        preset="secondary"
        icon="va-arrow-right"
        aria-label="Next page"
        :disabled="$props.pagination.page === totalPages"
        @click="$props.pagination.page++"
      />
      <VaPagination
        v-model="$props.pagination.page"
        buttons-preset="secondary"
        :pages="totalPages"
        :visible-pages="5"
        :boundary-links="false"
        :direction-links="false"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.va-data-table {
  ::v-deep(.va-data-table__table-tr) {
    border-bottom: 1px solid var(--va-background-border);
  }
}

// .description:hover {
//   overflow: visible; /* 鼠标悬浮时显示全部内容 */
//   white-space: normal; /* 允许文本换行，根据实际需求选择是否换行 */
// }
</style>
